package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.scyx.impl;
import org.apache.axis2.jaxws.utility.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;

/**
 * Created by ${yangsy} on 2017/3/17.
 */
public class ReflectUtil {
    private static Logger logger = LoggerFactory.getLogger(ReflectUtil.class);
    /**
     * 通过 反射  获取特性值
     *
     * @param obj       反射对象
     * @param tableName 反射里面的特性
     * @param fileds    反射特性里面的属性
     * @return
     */
    public static String reflectGetValue(Object obj, String tableName, String fileds) {
        String value = "";
        try {
            Class clazz = obj.getClass();
            PropertyDescriptor pd = new PropertyDescriptor(tableName, clazz);
            if (pd == null) return value;
            //  获得get方法
            Method getMethod = pd.getReadMethod();
            if (getMethod == null) return value;
            //  执行get方法返回一个Object
            Object object = getMethod.invoke(obj);
            if (object == null) return value;

            // 对象里面 的对象
            pd = new PropertyDescriptor(fileds, object.getClass());
            if (pd == null) return value;
            //  获得get方法
            getMethod = pd.getReadMethod();
            if (getMethod == null) return value;
            object = getMethod.invoke(object);
            //  获取当前属性 的类型  时间类型
            if (getMethod.getReturnType().toString().equals("class java.util.Date")) {
                if(object!=null){
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    object = format.format(object);
                }
            } else {
                object = ConvertUtils.convert(object, pd.getPropertyType());
            }
            value = (String) object;
        } catch (Exception e) {
            logger.error("类型转换异常:"+e.getMessage());
            e.printStackTrace();
        }
        return value;
    }
}
